import React from 'react'
import PropTypes from 'prop-types'
import './style.css'

class Regulable extends React.Component {
    static defaultProps = {
      drag: true,
      rotate: true,
      resize: {
        n: true,
        e: true,
        s: true,
        w: true
      },
      onChangeStyle() {}
    }

    static propTypes = {
      drag: PropTypes.bool,
      rotate: PropTypes.bool,
      resize: PropTypes.objectOf(PropTypes.bool),
      onChangeStyle: PropTypes.func
    }

    handleMouseDown = (key, event) => {
      this.originalX = event.clientX
      this.originalY = event.clientY
      document.addEventListener('mousemove', this.handleMouseMove)
      document.addEventListener('mouseup', this.handleMouseUp)
    }

    handleMouseMove = (event) => {
      const left = event.clientX - this.originalX
      const top = event.clientY - this.originalY
      this.updateStyle({
        left,
        top
      })
    }

    handleMouseUp = (event) => {
      document.removeEventListener('mousemove', this.handleMouseMove)
      document.removeEventListener('mouseup', this.handleMouseUp)
    }

    updateStyle = (style) => {
      this.props.onChangeStyle(style)
    }

    render = () => {
      const config = {
        drag: this.props.drag,
        rotate: this.props.rotate,
        resizeN: this.props.resize.n,
        resizeE: this.props.resize.e,
        resizeS: this.props.resize.s,
        resizeW: this.props.resize.w,
        resizeNE: this.props.resize.n && this.props.resize.e,
        resizeSE: this.props.resize.s && this.props.resize.e,
        resizeSW: this.props.resize.s && this.props.resize.w,
        resizeNW: this.props.resize.n && this.props.resize.w
      }

      return Object.keys(config)
        .filter(key => config[key])
        .map(key => < div className = {
            key
          }
          key = {
            key
          }
          onMouseDown = {
            this.handleMouseDown.bind(this, key)
          }
          />)
        }
    }

    export default Regulable
